#encoding:utf-8

from django.http import HttpResponse,HttpResponseRedirect
from login.models import Register
from django.core.urlresolvers import reverse
from django.shortcuts import render
from users.models import Info,Teacher,News,Review_of_news,Message,Follow_topic,Follow_user,Follow_group,Follow_course,Post_reward,Post_course,Purchase,Good_news,Good_review_of_news,Warning_mes
from groups.models import Group,Topic,Review_of_topic,Good_review_of_topic,Group_file
from rewards.models import Reward,Uncover,Reward_mes,Reward_course,Reward_lession
from courses.models import Types,Tiny_type,Course,Lession,Course_comment
from application.models import Bad,Data,Invite
from email.mime.text import MIMEText
import sys,time,datetime,os,smtplib,md5
reload(sys)
sys.setdefaultencoding('utf-8')
import re,md5,os,time,json,base64,qiniu.io,qiniu.conf,qiniu.rs,math

#登入 需要注意，Register表内的用户status为2时，是管理员
def login (request) :
    try :
        user=Register.objects.filter(status=2).get(email=request.POST['email'])
        if (user.password==md5.new(request.POST['password']).hexdigest()) :
            request.session['app_id']=user.id
            return HttpResponseRedirect(reverse('applications:index'))
        else :
            return HttpResponse("用户名与密码不匹配！")
    except :
        return render(request,"application/login.html")

#后台首页数据显示
def index (request) :
    #拿出从七个月前到当前月每个月的：课程申请数统计 & 小组发布数统计
    now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    nowyear=int(now.split('-')[0])
    lastyear=0
    nowmonth=int(now.split(' ')[0].split('-')[1])
    months=[]
    month=nowmonth
    groupcount=[]
    coursecount=[]
    if nowmonth>6:
        b=0
        while b<7:
            themonth=nowmonth-b
            months.append(themonth)
            b+=1
            group=Group.objects.filter(time__year=nowyear).filter(time__month=themonth).count()
            course=Course.objects.filter(time__year=nowyear).filter(time__month=themonth).count()
            groupcount.append(group)
            coursecount.append(course)
    else:
        a=0
        while month>0:
            months.append(month)
            group=Group.objects.filter(time__year=nowyear).filter(time__month=month).count()
            course=Course.objects.filter(time__year=nowyear).filter(time__month=month).count()
            groupcount.append(group)
            coursecount.append(course)
            month-=1

        while len(months)<7:
            months.append(12-a)
            group=Group.objects.filter(time__year=(nowyear-1)).filter(time__month=month).count()
            course=Course.objects.filter(time__year=(nowyear-1)).filter(time__month=month).count()
            groupcount.append(group)
            coursecount.append(course)
            a+=1
    #麦知网用户统计
    ordinary_user_count=Info.objects.filter(status=1).count()
    publisher_count=Info.objects.filter(status=2).count()
    #麦知网举报数据统计 & 麦知网审核数据统计
    data=Data.objects.get(id=1)
    #以后用
    purchase_ids=[]
    purchase_set=Purchase.objects.all()
    for p in purchase_set:
        purchase_ids.append(p.purchase_id)
    #麦知网数据统计
    #按大分类分别显示  未成交悬赏	制作中悬赏	已完成悬赏	课程发布数	课程交易量
    otherdata=[]
    types=Types.objects.all()
    for t in types:
        each=[]
        try:
            reward1_con=Reward.objects.filter(status=1).filter(types_id=t.id).count()
        except:
            reward1_con=0
        try:
            reward2_con=Reward.objects.filter(status=2).filter(types_id=t.id).count()
        except:
            reward2_con=0
        try:
            reward3_con=Reward.objects.filter(status=3).filter(types_id=t.id).count()
        except:
            reward3_con=0
        tiny_types_in_t=[]
        tiny_types_in_t_set=Tiny_type.objects.filter(types_id=t.id)
        for tiny in tiny_types_in_t_set:
            tiny_types_in_t.append(tiny.id)
        try:
            courses_con=Course.objects.filter(tiny_type_id__in=tiny_types_in_t).count()
        except:
            courses_con=0
        purchase_con=t.purchase_con
        #purchase_con=Course.objects.filter(tiny_type_id__in=tiny_types_in_t).filter(id__in=purchase_ids).count()

        each.append(t.name)			#0
        each.append(reward1_con)	#1
        each.append(reward2_con)	#2
        each.append(reward3_con)	#3
        each.append(courses_con)	#4
        each.append(purchase_con)	#5
        otherdata.append(each)


    return render(request,"application/index.html",{'otherdata':otherdata,'data':data,'publisher_count':publisher_count,
                                                    'ordinary_user_count':ordinary_user_count,'coursecount':coursecount,'groupcount':groupcount,'months':months})

#被举报的小组
def groups (request) :
    bad_groups_set=Bad.objects.filter(status=2)
    bad_groups=[]
    for b in bad_groups_set:
        each=[]
        each.append(b.id)			#0
        each.append(b.bad_id)		#1
        each.append(b.content)		#2
        bad_name=Group.objects.get(id=b.bad_id).name
        each.append(bad_name)		#3
        bad_groups.append(each)

    return render(request,"application/groups.html",{'bad_groups':bad_groups})

#申请小组的页面展示
def ifgroup (request) :
    app_group_set=Group.objects.filter(status=1)
    app_group=[]
    for a in app_group_set:
        each=[]
        each.append(a.id)		#0
        each.append(a.user_id)	#1
        user_name=Info.objects.get(user_id=a.user_id).user_name
        each.append(user_name)	#2
        each.append(a.name)		#3
        each.append(a.introduce)	#4
        each.append(a.domain)		#5
        each.append(a.img)		#6
        app_group.append(each)

    return render(request,"application/ifgroup.html",{'app_group':app_group})

#被举报的课程
def courses (request) :
    bad_course_set=Bad.objects.filter(status=3)
    bad_course=[]
    for b in bad_course_set:
        each=[]
        each.append(b.id)		#0
        each.append(b.bad_id)	#1
        course_name=Course.objects.get(id=b.bad_id).name
        each.append(course_name)	#2
        each.append(b.content)	#3
        bad_course.append(each)

    return render(request,"application/courses.html",{'bad_course':bad_course})

#被举报的悬赏
def rewards (request) :
    bad_reward_set=Bad.objects.filter(status=4)
    bad_reward=[]
    for b in bad_reward_set:
        each=[]
        each.append(b.id)		#0
        each.append(b.bad_id)	#1
        reward_name=Reward.objects.get(id=b.bad_id).name
        each.append(reward_name)	#2
        each.append(b.content)	#3
        bad_reward.append(each)

    return render(request,"application/rewards.html",{'bad_reward':bad_reward})

#被举报的用户
def users (request) :
    bad_user_set=Bad.objects.filter(status=1)
    bad_user=[]
    for b in bad_user_set:
        each=[]
        each.append(b.id)		#0
        each.append(b.bad_id)	#1
        user_name=Info.objects.get(user_id=b.bad_id).user_name
        each.append(user_name)	#2
        each.append(b.content)	#3
        bad_user.append(each)

    return render(request,"application/users.html",{'bad_user':bad_user})

#用户申请的页面展示
def publisher (request) :
    the_teacher_set=Teacher.objects.filter(status=0).order_by("id")[0:1]
    if the_teacher_set:
        for t in the_teacher_set:
            the_teacher=t
        return render(request,"application/publisher.html",{'the_teacher':the_teacher})
    else:
        return HttpResponse('无发布者申请')

#增加一条被举报内容 .
#status由ajax传进来。status=1：被举报用户； status=2：被举报小组； status=3：被举报课程； status=4：被举报悬赏；
def addbad (request) :
    bad_id=request.GET['bad_id']
    status=request.GET['status']
    content=''
    if 'content' in request.GET:
        content=request.GET['content']

    bad=Bad(bad_id=bad_id,user_id=request.session['id'],content=content,status=status)
    bad.save()

    return HttpResponse('1')

#警告被举报小组的发布者
def badwarning (request) :
    theid=int(request.GET['theid'])
    bad=Bad.objects.get(id=theid)
    group=Group.objects.get(id=bad.bad_id)
    bad_name=group.name
    user_id=group.user_id
    bad_content=bad.content
    #bad.warning_con+=1
    #bad.save()
    bad.delete()

    data=Data.objects.get(id=1)
    data.bad_group_con+=1
    data.save()
    #if bad.content=='':
    #	mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的小组'+bad_name+'被举报,请尽快整改。')
    #	mes.save()
    #else:
    #	mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的小组'+bad_name+'被举报,请尽快整改。举报原因：'+bad_content)
    #	mes.save()
    mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的小组'+bad_name+'被举报,请尽快整改。举报原因：'+bad_content)
    mes.save()
    return HttpResponse('1')

#警告被举报课程的发布者
def bad_course_warning (request) :
    theid=int(request.GET['theid'])
    bad=Bad.objects.get(id=theid)
    course=Course.objects.get(id=bad.bad_id)
    bad_name=course.name
    user_id=course.teacher_id
    bad_content=bad.content
    #bad.warning_con+=1
    #bad.save()
    bad.delete()

    data=Data.objects.get(id=1)
    data.bad_course_con+=int(1)
    data.save()

    mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的课程'+bad_name+'被举报,请尽快整改。举报原因：'+bad_content)
    mes.save()
    return HttpResponse('1')

#警告被举报悬赏的发布者
def bad_reward_warning (request) :
    theid=int(request.GET['theid'])
    bad=Bad.objects.get(id=theid)
    reward=Reward.objects.get(id=bad.bad_id)
    bad_name=reward.name
    user_id=reward.from_id
    bad_content=bad.content
    #bad.warning_con+=1
    #bad.save()
    bad.delete()

    data=Data.objects.get(id=1)
    data.bad_reward_con+=int(1)
    data.save()

    mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的悬赏'+bad_name+'被举报,请尽快整改。举报原因：'+bad_content)
    mes.save()
    return HttpResponse('1')

#警告被举报用户
def bad_user_warning (request) :
    theid=int(request.GET['theid'])
    bad=Bad.objects.get(id=theid)
    bad_content=bad.content
    bad_id=bad.bad_id
    #bad.warning_con+=1
    #bad.save()
    bad.delete()

    data=Data.objects.get(id=1)
    data.bad_user_con+=int(1)
    data.save()

    mes=Message(status=1,from_id=request.session['app_id'],to=bad_id,content='您被举报,请尽快整改。举报原因：'+bad_content)
    mes.save()
    return HttpResponse('1')

#忽略举报内容
def notbad (request) :
    theid=int(request.GET['theid'])
    bad=Bad.objects.get(id=theid)
    status=bad.status
    bad.delete()

    data=Data.objects.get(id=1)
    if status==1:
        data.good_user_con+=int(1)
        data.save()
    if status==2:
        data.good_group_con+=int(1)
        data.save()
    if status==3:
        data.good_course_con+=int(1)
        data.save()
    if status==4:
        data.good_reward_con+=int(1)
        data.save()

    return HttpResponse('1')

#通过小组申请
def pass_group (request) :
    groupid=int(request.GET['groupid'])
    thegroup=Group.objects.get(id=groupid)
    user_id=thegroup.user_id
    group_name=thegroup.name
    thegroup.status=2
    thegroup.save()

    data=Data.objects.get(id=1)
    data.pass_group_con+=1
    data.save()

    mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的小组'+group_name+'通过审核')
    mes.save()
    Follow_group(user_id=user_id,follow_group_id=groupid,status='1',topic_con='0',good_con='0',review_con='0',file_con='0').save()
    return HttpResponse('1')

#驳回小组申请
def nopass (request) :
    groupid=int(request.GET['groupid'])
    nopass_content=''
    if 'nopass_content' in request.GET:
        nopass_content=request.GET['nopass_content']
    thegroup=Group.objects.get(id=groupid)
    user_id=thegroup.user_id
    group_name=thegroup.name
    img=thegroup.img
    thegroup.delete()
    qiniu.rs.Client().delete('mzgroup',img)

    if nopass_content=='':
        mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的小组'+group_name+'未通过审核')
        mes.save()
    else:
        mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的小组'+group_name+'未通过审核,原因是：'+nopass_content)
        mes.save()

    data=Data.objects.get(id=1)
    data.not_group_con+=1
    data.save()

    return HttpResponse('1')

#通过发布者申请
def passPublisher (request) :
    tea_id=request.GET['tea_id']
    user_id=Teacher.objects.get(id=tea_id).user_id
    info=Info.objects.get(user_id=user_id)
    info.status=2
    info.save()

    thetea=Teacher.objects.get(id=tea_id)
    thetea.status=int(1)
    thetea.save()

    data=Data.objects.get(id=1)
    data.pass_publisher_con+=1
    data.save()

    mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='恭喜您，您的发布者资格申请通过，请开始麦知之旅。')
    mes.save()
    return HttpResponse('1')

#驳回发布者申请
def notPublisher (request) :
    tea_id=request.GET['tea_id']
    the_tea=Teacher.objects.get(id=tea_id)
    user_id=the_tea.user_id
    identity_img=str(the_tea.identity_img)
    the_tea.delete()

    mes=Message(status=1,from_id=request.session['app_id'],to=user_id,content='您的教师申请未能通过审核，请在申请中详细填写您的真实信息，并上传清晰的身份证照片')
    mes.save()

    os.remove('templates/picture/ID/'+identity_img)

    data=Data.objects.get(id=1)
    data.not_publisher_con+=1
    data.save()

    return HttpResponse('1')

#申请内测资格显示页面
def invite (request) :
    invite=Invite.objects.filter(status=0)

    return render(request,"application/invite.html",{'invite':invite})

#内测资格通过
def passuser (request) :
    invite_id=request.GET['inviteid']
    the_invite=Invite.objects.get(id=invite_id)
    email=str(the_invite.email)
    reg=Register(email=email,password=the_invite.password,status=1)
    reg.save()
    user_id=reg.id
    info=Info(user_id=user_id,user_name='新用户',status=1,work=the_invite.work,position=the_invite.position,sex=the_invite.sex,img='default.png',domain='http://mzhead.qiniudn.com/')
    info.save()
    Follow_user(user_id=user_id,follow_user_id=user_id).save()
    the_invite.status=1
    the_invite.save()
    #发邮件通知
    user='mzclub'+str(user_id)
    token=md5.new(user).hexdigest()
    mailto_list=email
    mail_host="smtp.exmail.qq.com"
    mail_name="麦知网"
    mail_user="service@mazclub.com"
    mail_pass="maizhi123"
    mail_postfix="mazclub.com"
    me=mail_name+"<"+mail_user+"@"+mail_postfix+">"

    #msg = MIMEText('<html><h1>您好：</h1>欢迎来到麦知网！<div><a href="/addmajor/?u='+str(user_id)+'&token='+str(token)+'">点击访问麦知网</div><hr/><br/>麦知网服务团队<br/>客户问题建议反馈 ： feedback@mazclub.com<br/>企业战略合作联系 ： cooperation@mazclub.com<br/></html>','html','utf-8')
    html = u'<html><h1>您好：</h1>欢迎来到麦知网！这是一个因为知识而联系在一起的圈子，在这里您可以与朋友在互动中发现并学习知识<br/>'\
                   u'也可以将您的知识与见解分享给其他人，让更多的人感受并真切体验到追求知识的快乐!<br/>在这里您将体验：<br/><b>小组:</b>'\
                   u'找到志趣相投者，不亦乐乎。<br/><b>课程:</b>发现有价值的知识，不亦快乎。<br/><b>悬赏:</b>三人行，必有我师，坦诚相待，不亦君子乎。<br/>'\
                   u'祝您学习愉快！<br/><div><a href="http://demo.mazclub.com/addmajor/?u=%s&token=%s' \
                   u'">点击访问麦知网</a></div><hr/><br/>麦知网服务团队<br/>客户问题建议反馈 ： feedback@mazclub.com' \
                   u'<br/>企业战略合作联系 ： cooperation@mazclub.com<br/></html>' % (str(user_id), str(token))
    msg = MIMEText(html,'html','utf-8')
    #content="/verification/?key="+base64.encodestring(address)+"\n您好：\n欢迎来到麦知网！这是一个因为知识而联系在一起的圈子，在这里您可以与朋友在互动中发现并学习知识\n也可以将您的知识与见解分享给其他人，让更多的人感受并真切体验到追求知识的快乐!\n在这里您将体验：\n小组:找到志趣相投者，不亦乐乎。\n课程:发现有价值的知识，不亦快乎。\n悬赏:三人行，必有我师，坦诚相待，不亦君子乎。\n更多乐趣请到  www.mazclub.com\n祝您学习愉快！\n麦知网服务团队\n客户问题建议反馈 ： feedback@mazclub.com\n企业战略合作联系 ： cooperation@mazclub.com\n"
    #msg = MIMEText(content)
    msg['Subject'] = '您的用户申请已通过审核--麦知网'
    msg['From'] = me
    msg['To'] = mailto_list
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, mailto_list, msg.as_string())
        s.quit()
        return HttpResponse('1')
    except Exception as e:
        #print str(e)
        return HttpResponse('2')

#内测资格被驳回;
def notuser (request) :
    invite_id=request.GET['inviteid']
    the_invite=Invite.objects.get(id=invite_id)
    email=str(the_invite.email)
    the_invite.status=2
    the_invite.save()

    mailto_list=email
    mail_host="smtp.exmail.qq.com"
    mail_name="麦知网"
    mail_user="service@mazclub.com"
    mail_pass="maizhi123"
    mail_postfix="mazclub.com"
    me=mail_name+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText('<html><h1>您好：</h1><div>很抱歉，您的用户申请未能通过审核。祝您工作顺利！</div></html>','html','utf-8')
    #content="/verification/?key="+base64.encodestring(address)+"\n您好：\n欢迎来到麦知网！这是一个因为知识而联系在一起的圈子，在这里您可以与朋友在互动中发现并学习知识\n也可以将您的知识与见解分享给其他人，让更多的人感受并真切体验到追求知识的快乐!\n在这里您将体验：\n小组:找到志趣相投者，不亦乐乎。\n课程:发现有价值的知识，不亦快乎。\n悬赏:三人行，必有我师，坦诚相待，不亦君子乎。\n更多乐趣请到  www.mazclub.com\n祝您学习愉快！\n麦知网服务团队\n客户问题建议反馈 ： feedback@mazclub.com\n企业战略合作联系 ： cooperation@mazclub.com\n"
    #msg = MIMEText(content)
    msg['Subject'] = '您的用户申请审核结果--麦知网'
    msg['From'] = me
    msg['To'] = mailto_list
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, mailto_list, msg.as_string())
        s.quit()
        return HttpResponse('1')
    except Exception, e:
        #print str(e)
        return HttpResponse('2')
    return HttpResponse('1')